package com.abe.mvp.view.activity;

import java.io.File;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.abe.app.RelayoutTool;
import com.abe.config.Constants;
import com.abe.config.ExerciseReportUtil;
import com.abe.config.HttpUtils;
import com.abe.config.SettingParam;
import com.abe.mvp.model.bean.ExerciseShowBean;
import com.abe.mvp.model.bean.MainTopBean;
import com.abe.mvp.model.bean.exercise.ExerciseGroupBean;
import com.abe.mvp.model.bean.http.ExerciseDataBean;
import com.abe.mvp.model.bean.http.HttpBean;
import com.abe.mvp.view.activity.base.BaseActivity;
import com.abe.threadmill.R;
import com.abe.utils.JsonHelper;
import com.abe.utils.NetUtils;
import com.abe.utils.NormalUtils;
import com.squareup.picasso.Picasso;

@SuppressLint({ "InflateParams", "SimpleDateFormat" })
@ContentView(R.layout.activity_exercise_data)
public class ExerciseDataActivity extends BaseActivity {

	@ViewInject(R.id.show_exercise_button_back)
	private LinearLayout show_exercise_button_back;
	@ViewInject(R.id.show_exercise_logo)
	private ImageView show_exercise_logo;

	@ViewInject(R.id.tabmenu_layout)
	private ImageView tabmenu_layout;

	@ViewInject(R.id.exercise_list)
	private GridView exercise_list;
	private ExerciseAdapter adapter;
	private List<MainTopBean> beans;

	/********************** 锻炼数据 ************************/
	private ExerciseShowBean showBean;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initBackground();
		initView();
	}

	private void initBackground() {
		/** 菜单页背景 */
		Picasso.with(this).load(R.drawable.run_image_bg_05).centerCrop()
				.placeholder(R.drawable.app_theme_bg).resize(1280, 720)
				.into(tabmenu_layout);
	}

	private void initView() {
		show_exercise_button_back.setVisibility(View.VISIBLE);
		show_exercise_logo.setVisibility(View.VISIBLE);
		/** 数据 */
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			ExerciseGroupBean groupBean = (ExerciseGroupBean) bundle
					.get("exercise");
			/** 本地缓存 */
			ExerciseReportUtil.saveExercise(groupBean);
			if (current_user.getFlag() != SettingParam.flag_user_tourist) {
				/** 数据上传 */
				SimpleDateFormat format = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				List<ExerciseDataBean> dataBeans = new ArrayList<ExerciseDataBean>();
				ExerciseDataBean data = new ExerciseDataBean();
				data.setDuration(String.valueOf(groupBean.getKeepTime()));
				data.setCalorie((int) groupBean.getCalorie());
				data.setTime(format.format(new Date()));
				data.setTimes(1);
				data.setDistance(String.valueOf(Constants.keepDecimal(
						groupBean.getDistance() / 1000, 1)));
				data.setDeclivity((int) groupBean.getAverageSlope());
				data.setHeart_rate(0);
				data.setSpeed((int) Constants.SpeedConvertByMS(groupBean
						.getAverageSpeed()));
				dataBeans.add(data);
				uploadExercise(current_user.getUser().getOpenid(),
						NetUtils.getLocalMacAddressFromWifiInfo(),
						JsonHelper.toJson(dataBeans));
			}
			/********************************************************************/
			/** 展示数据 */
			showBean = new ExerciseShowBean();
			showBean.setTime(Constants.formatTime(groupBean.getKeepTime()));
			showBean.setBpm("0");
			showBean.setKcal(String.valueOf((int) groupBean.getCalorie())
					+ "(Kcal)");
			showBean.setDistance(String.valueOf(Constants.keepDecimal(
					groupBean.getDistance() / 1000, 2)));
			showBean.setStep(String.valueOf(Constants.getSteps(groupBean
					.getDistance())));
			showBean.setSpeed(String.valueOf(Constants.keepDecimal(
					Constants.SpeedConvertByMS(groupBean.getAverageSpeed()), 1)));
			showBean.setSlope(String.valueOf(Constants.keepDecimal(
					groupBean.getAverageSlope(), 1)));

			String[] datas = new String[6];
			datas[0] = showBean.getTime();
			datas[1] = showBean.getStep();
			datas[2] = showBean.getKcal();
			datas[3] = showBean.getDistance();
			datas[4] = showBean.getSpeed();
			datas[5] = showBean.getSlope();

			/** 组装 */
			beans = new ArrayList<MainTopBean>();
			int[] names = { R.string.common_time, R.string.common_step_number,
					R.string.common_calorie, R.string.common_distance,
					R.string.common_speed, R.string.common_slope };
			int[] units = { R.string.empty, R.string.empty,
					R.string.common_report_cll_unit,
					R.string.common_distance_unit, R.string.common_speed_unit,
					R.string.common_slope_unit };
			int drawable[] = { R.drawable.icon_dlsj, R.drawable.icon_dlcs,
					R.drawable.icon_dlkll, R.drawable.icon_dlcs,
					R.drawable.icon_dlcs, R.drawable.icon_dlcs };

			/** 初始化顶部信息 */
			for (int i = 0; i < 6; i++) {
				MainTopBean info = new MainTopBean();
				info.setName(NormalUtils.getString(names[i]));
				info.setData(datas[i]);
				info.setImage(drawable[i]);
				info.setType(Integer.class);
				info.setUnit(NormalUtils.getString(units[i]));
				beans.add(info);
			}
			adapter = new ExerciseAdapter();
			exercise_list.setAdapter(adapter);
		}
	}

	@Event(value = R.id.show_exercise_button_back, type = View.OnClickListener.class)
	private void back(View view) {
		back();
	}

	private void uploadExercise(String openid, String mac, String trainningData) {
		String URL = HttpUtils.GetUrl(HttpUtils.API_UPLOAD_EXERCISE_DATA);
		RequestParams params = new RequestParams(URL);
		params.addBodyParameter("openid", openid);
		params.addBodyParameter("mac", mac);
		params.addBodyParameter("device_type", "1");
		params.addBodyParameter("trainningData", trainningData);
		x.http().post(params, new Callback.CommonCallback<String>() {

			@Override
			public void onCancelled(CancelledException exception) {

			}

			@Override
			public void onError(Throwable throwable, boolean arg1) {

			}

			@Override
			public void onFinished() {

			}

			@Override
			public void onSuccess(String result) {
				@SuppressWarnings("rawtypes")
				HttpBean bean = JsonHelper.parseObject(result, HttpBean.class);
				if (bean.getSuccess() != 1) {
					showToast(bean.getMessage());
				} else {
					showToast("上传成功");
				}
			}
		});
	}

	@Event(value = R.id.show_exercise_button_back, type = View.OnClickListener.class)
	private void buttonBack(View view) {
		back();
	}

	/********************************* web服务相关 **************************************/

	class ExerciseAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return beans.size();
		}

		@Override
		public Object getItem(int position) {
			return beans.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				// 获得组件，实例化组件
				convertView = LayoutInflater.from(ExerciseDataActivity.this)
						.inflate(R.layout.item_list_exercise_data, null);
				RelayoutTool.relayoutViewHierarchy(convertView, scale);
				viewHolder.layout = (LinearLayout) convertView
						.findViewById(R.id.item_report_layout);
				viewHolder.name = (TextView) convertView
						.findViewById(R.id.item_report_name);
				viewHolder.num = (TextView) convertView
						.findViewById(R.id.item_report_num);
				viewHolder.unit = (TextView) convertView
						.findViewById(R.id.item_report_unit);
				viewHolder.image = (ImageView) convertView
						.findViewById(R.id.item_report_image);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			MainTopBean bean = beans.get(position);
			viewHolder.name.setText(bean.getName());
			viewHolder.num.setText(bean.getData());
			viewHolder.unit.setText(bean.getUnit());
			setDrawable(viewHolder.image, bean.getImage(), bean.getType());

			return convertView;
		}

		private void setDrawable(ImageView imageView, Object load, Type type) {

			if (type.equals(String.class)) {
				Picasso.with(ExerciseDataActivity.this).load((String) load)
						.into(imageView);
			} else if (type.equals(Uri.class)) {
				Picasso.with(ExerciseDataActivity.this).load((Uri) load)
						.into(imageView);
			} else if (type.equals(File.class)) {
				Picasso.with(ExerciseDataActivity.this).load((File) load)
						.into(imageView);
			} else if (type.equals(Integer.class)) {
				Picasso.with(ExerciseDataActivity.this).load((Integer) load)
						.into(imageView);
			}
		}

		class ViewHolder {
			public LinearLayout layout;
			public TextView name;
			public TextView num;
			public TextView unit;
			public ImageView image;
		}
	}
}
